package yhp.com.zijie.dao.impl;

import yhp.com.zijie.bean.Role;
import yhp.com.zijie.bean.Users;
import yhp.com.zijie.dao.UsersDao;
import yhp.com.zijie.util.DBUtils;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UsersDaoImpl extends DBUtils implements UsersDao {


    @Override
    public Users login(String username, String password) {


        Users users = null;
        try {
            String sql = "select * from users where loginname=? and password=?";
            List list = new ArrayList();
            list.add(username);
            list.add(password);
            resultSet = query(sql, list);

            if (resultSet == null){
                return null;
            }

            while (resultSet.next()){
                users = new Users();
                users.setLoginName(username);//因为走到这说明该用户存在，说明昵称是对的
                users.setRealName(resultSet.getString("realname"));
                users.setUserId(resultSet.getInt("userid"));

                users.setRoleId(resultSet.getInt("roleid"));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            closeAll();
        }

        return users;
    }


    @Override
    public List<Users> getUsersList(int pageIndex, int pageSize) {

        List<Users> usersList = new ArrayList<>();

        try {
            String sql = "SELECT u.userid, u.loginname , u.realname , r.rolename from users u,role r where u.roleid=r.roleid limit ?,?";
            List params = new ArrayList();
            params.add((pageIndex-1)*pageSize);
            params.add(pageSize);
            resultSet = query(sql, params);

            while (resultSet.next()){
                Users users = new Users();
                users.setUserId(resultSet.getInt("userid"));
                users.setLoginName(resultSet.getString("loginname"));
                users.setRealName(resultSet.getString("realname"));

                Role role = new Role();
                role.setRoleName(resultSet.getString("rolename"));

                //建立表关系
                users.setRole(role);
                usersList.add(users);

            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            closeAll();
        }


        return usersList;
    }

    @Override
    public int total() {
        int total = 0;

        try {
            String sql = "select count(*) from users u,role r where u.roleid=r.roleid ";

            resultSet = query(sql, null);

            while (resultSet.next()){
                total = resultSet.getInt(1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            closeAll();
        }

        return total;
    }


}














